//
//  UIImageView+Extension.swift
//  AispeechMobileApp
//
//  Created by Lee on 2019/3/6.
//  Copyright © 2019年 Lee. All rights reserved.
//

import UIKit

extension UIImageView {
    
    // 添加动画 动画执行一次时长
    func addAnimation(duration:CGFloat) {
        let monkeyAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        monkeyAnimation.toValue = Double.pi * 2
        monkeyAnimation.duration = CFTimeInterval(duration)
        monkeyAnimation.timingFunction = CAMediaTimingFunction.init(name: .linear)
        monkeyAnimation.isCumulative = false
        monkeyAnimation.isRemovedOnCompletion = false
        monkeyAnimation.fillMode = .forwards
        monkeyAnimation.repeatCount = MAXFLOAT
        self.layer.add(monkeyAnimation, forKey: "AnimatedKey")
        self.stopAnimating()
        self.layer.speed = 0.0
    }
    
    // 停止
    func pausedRotating() {
        let pausedTime = self.layer.convertTime(CACurrentMediaTime(), from: nil)
        self.layer.speed = 0.0
        self.layer.timeOffset = pausedTime
    }
    
    // 恢复
    func resumeRotate() {
        let pausedTime = self.layer.timeOffset
        self.layer.speed = 1.0
        self.layer.timeOffset = 0.0
        self.layer.beginTime = 0.0
        let timeWhenpause = self.layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
        self.layer.beginTime = timeWhenpause
    }
    
    // 移除
    func removeAnimation() {
        self.layer.removeAllAnimations()
    }
    
    // 重新开始旋转（移除 -> 添加 -> 恢复）
    func restartRotate(duration:CGFloat) {
        removeAnimation()
        addAnimation(duration: duration)
        resumeRotate()
    }
    
}
